<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src='lib/webgl-utils.js'></script>
    <script src='lib/webgl-debug.js'></script>
    <script src='lib/cuon-utils.js'></script>
</head>
<body onload="main()">
<canvas id="mybox" width="500" height="400">
    请更换新版浏览器查看效果!
</canvas>
<script>
    //attribute变量都以a_开头
    //uniform变量都以u_开头
    let VSHADER_SOURCE=
        'attribute vec4 a_position;void main(){gl_Position=a_position;gl_PointSize=10.0;}';
    let FSHADER_SOURCE=
        'void main(){gl_FragColor=vec4(1.0,0.0,0.0,1.0);}';
    let g_points=[];

    function main(){
        let canvas=document.getElementById('mybox');
        let gl=getWebGLContext(canvas);
        if(!gl){
            console.log('WebGl 获取失败');
            return;
        }
        if(!initShaders(gl,VSHADER_SOURCE,FSHADER_SOURCE)){
            console.log('初始化shaders失败');
            return;
        }
        let a_position=gl.getAttribLocation(gl.program,'a_position')
        canvas.onmousedown=e=>{
            clicked(e,gl,canvas,a_position)
        }
    }

    function clicked(event,gl,canvas,a_position){
        let x=event.clientX;
        let y=event.clientY;
        let rect=event.target.getBoundingClientRect();
        //此时以canvas正中心的点为原点
        //canvas横坐标/webGL横坐标=canvas宽/2
        //webGL Y方向与canvas中相反
        let posX=((x-rect.left)-canvas.width/2)/(canvas.width/2);
        let posY=(canvas.height/2-(y-rect.top))/(canvas.height/2);
        g_points.push([posX,posY]);
        console.log(g_points)
        gl.clearColor(0.0,0.0,0.0,1.0);
        gl.clear(gl.COLOR_BUFFER_BIT);
        g_points.forEach((value)=>{
            gl.vertexAttrib3f(a_position,value[0],value[1],0.0);
            gl.drawArrays(gl.POINTS,0,1)
        })

    }





</script>

</body>
</html>